<template>
  <header>
    <div class="w1200">
      <el-menu :default-active="route.name" router class="el-menu-demo" mode="horizontal">
        <el-menu-item index="home" :route="{name: 'home'}">Home</el-menu-item>
        <el-menu-item index="ranking" :route="{name: 'ranking'}">Ranking</el-menu-item>
        <el-menu-item index="user" :route="{name: 'user'}" v-if="userStore.account">My NFT</el-menu-item>
      </el-menu>
      <div class="account">
        <el-button type="primary" v-if="!userStore.account" :icon="Connection" @click="handleConnect">Connect Wallet
        </el-button>
        <template v-else>
          <el-button type="primary" @click="handleCopy" :icon="Wallet" round>{{userStore.address}}</el-button>
          <el-button circle :icon="SwitchButton" type="danger" @click="handleDisconnect"></el-button>
        </template>
      </div>
    </div>
  </header>
</template>

<script setup>
import { Wallet, Connection, SwitchButton } from '@element-plus/icons-vue'
import { onMounted, ref, getCurrentInstance } from "vue";
import { useRoute } from 'vue-router'
import { useEthersStore } from '@/stores/modules/providers'
import { ElNotification } from 'element-plus'

const route = useRoute()
const userStore = useEthersStore()

async function handleConnect () {
  try {
    await userStore.connect(true)
  } catch (error) {
    console.log('[ error ] >', error)
  }
}

function handleDisconnect () {
  userStore.disconnect()
}

const { proxy } = getCurrentInstance()
function handleCopy () {
  proxy.$clipboard(userStore.account).then(() => {
    ElNotification.success({
      message: 'Copy success',
      title: 'Success',
    })
  })
}

onMounted(async () => {
  const connectType = localStorage.getItem('connect_type')
  if (connectType) {
    try {
      await userStore.connect(false)
    } catch (error) {
      console.log('[ error ] >', error)
    }
  }
})

</script>

<style lang="less" scoped>
header {
  width: 100%;
  background-color: #fff;
  .w1200 {
    max-width: 1000px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 60px;
  }
  .el-menu-demo {
    flex: 1;
    border-bottom: 0;
  }
  .account {
  }
}
</style>
